package com.fj.netty.chat.handler;

import com.fj.netty.chat.message.GroupChatResponseMessage;
import com.fj.netty.chat.message.GroupJoinRequestMessage;
import com.fj.netty.chat.pojo.GroupChat;
import com.fj.netty.chat.server.service.GroupSession;
import com.fj.netty.chat.server.service.ServiceFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @author fj
 * @date 2024/1/12 16:19
 */
@Slf4j
public class GroupJoinResponseMessageHandler extends SimpleChannelInboundHandler<GroupJoinRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupJoinRequestMessage msg) throws Exception {
        GroupSession groupSession = ServiceFactory.getGroupSession();
        GroupChat groupChat = groupSession.join(msg.getUsername(), msg.getGroupName());
        Set<Channel> channels = groupSession.memberChannels(groupChat.getName());
        for (Channel channel:channels){
            GroupChatResponseMessage message = new GroupChatResponseMessage();
            message.setFrom("系统消息");
            message.setContent("加入群聊成功："+groupChat.getName());
            channel.writeAndFlush(message);
        }
    }
}
